package org.liziyi.pss.model.queue;

import org.liziyi.pss.entity.ProcessControlBlock;
import org.liziyi.pss.model.ScheduleQueue;
import org.liziyi.pss.util.ProcessUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.util.LinkedList;

/**
 * @author liziyi
 */
public abstract class AbstractScheduleQueue implements ScheduleQueue<ProcessControlBlock> {
    protected LinkedList<ProcessControlBlock> queueList;
    protected DefaultTableModel queueTableModel;
    @Override
    public synchronized ProcessControlBlock poll() {
        ProcessControlBlock pcb=queueList.poll();
        if(pcb!=null){
            SwingUtilities.invokeLater(()->{
                queueTableModel.removeRow(0);
            });
        }
        return pcb;
    }

    @Override
    public synchronized void add(ProcessControlBlock pcb) {
        queueList.add(pcb);
        SwingUtilities.invokeLater(()->{
            queueTableModel.addRow(ProcessUtil.pcb2TableRow(pcb));
        });
    }

    @Override
    public synchronized boolean isEmpty() {
        return queueList.isEmpty();
    }

    @Override
    public synchronized ProcessControlBlock remove(int index) {
        SwingUtilities.invokeLater(()->{
            queueTableModel.removeRow(index);
        });
        return queueList.remove(index);
    }

    @Override
    public void reset() {
        queueList.clear();
        queueTableModel.setRowCount(0);
    }

    public AbstractScheduleQueue(TableModel queueTableModel) {
        this.queueTableModel = (DefaultTableModel) queueTableModel;
        queueList=new LinkedList<>();
    }

    public LinkedList<ProcessControlBlock> getQueueList() {
        return queueList;
    }
}
